package com.fjsh.entity;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import lombok.Data;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.gateway.filter.FilterDefinition;
import org.springframework.cloud.gateway.handler.predicate.PredicateDefinition;
import org.springframework.cloud.gateway.route.RouteDefinition;
import java.io.Serializable;
import java.util.Date;
import java.util.List;

@Data
public class AppRoute implements Serializable {

    private String routeId;
    private Integer order;
    private String uri;
    private String predicates;
    private String filters;
    private Date updateTime;
    private Boolean delete; // 是否删除

    public AppRoute() {
    }

    public AppRoute(String routeId, Integer order, String uri) {
        this.routeId = routeId;
        this.order = order;
        this.uri = uri;
    }

    /**
     * 将 AppRoute 转换成 Gateway 的 RouteDefinition
     * @return
     */
    public RouteDefinition parseToRoute() throws JSONException {
        if (StrUtil.isBlank(routeId) || StrUtil.isBlank(uri)) {
            return null;
        }

        List<PredicateDefinition> predicateDefinitions = StringUtils.isBlank(predicates)
                ? null : JSONObject.parseArray(predicates, PredicateDefinition.class);

        List<FilterDefinition> filterDefinitions = StringUtils.isBlank(filters)
                ? null : JSONObject.parseArray(filters, FilterDefinition.class);

        AppRoute routeForCopy = new AppRoute("", order, uri);
        RouteDefinition routeDefinition = JSONObject.parseObject(JSONObject.toJSONString(routeForCopy), RouteDefinition.class);
        routeDefinition.setId(routeId);
        routeDefinition.setPredicates(predicateDefinitions);
        routeDefinition.setFilters(filterDefinitions);

        return routeDefinition;
    }

}